package bigoo.ds;

import static java.util.logging.Logger.GLOBAL_LOGGER_NAME;

import java.io.IOException;
import java.util.logging.Logger;

import bigoo.common.PeerEntry;
import bigoo.common.communication.AbstractCommunication;
import bigoo.common.communication.Message;
import bigoo.common.communication.MessageReceiver;
import bigoo.ds.message.GetPeersAnswerMessage;
import bigoo.ds.message.ImAliveAnswerMessage;
import bigoo.peer.message.GetPeersMessage;
import bigoo.peer.message.ImAliveMessage;

public class DiscoveryService implements MessageReceiver {

	public static final String DS_ID = "DiscoveryService";

	private Logger logger = Logger.getLogger(GLOBAL_LOGGER_NAME);
	private PeerDirectory directory = new PeerDirectory();
	private AbstractCommunication communication;

	public DiscoveryService(AbstractCommunication communication) {
		this.communication = communication;
		this.communication.addReceiver(this);
		this.communication.start();
	}

	@Override
	public void processMessage(Message msg) {

		String peerID = msg.getSenderID();
		Message answer = null;
		String msgID = msg.getMessageIdentifier();
		if (msgID.equals(ImAliveMessage.MSG_IDENTIFIER)) {
			ImAliveMessage m = (ImAliveMessage) msg;
			int lease = this.directory.insertOrUpdatePeer(m.getSenderID(), m.getAddress(), m.getPort());
			answer = new ImAliveAnswerMessage(DS_ID, lease, this.directory.getThreshold());
			logger.info("IM_ALIVE message received from " + m.getSenderID());
		} else if (msgID.equals(GetPeersMessage.MSG_IDENTIFIER)) {
			answer = new GetPeersAnswerMessage(DS_ID, this.directory.getSomePeers(peerID));
			logger.info("GET_PEERS message received from " + msg.getSenderID());
		}

		PeerEntry peer = this.directory.getPeer(peerID);

		try {
			if (answer != null && peer != null) {
				this.communication.sendMessage(answer, peer);
			}
		} catch (IOException ioex) {
			logger.warning("Error sending message to " + peer.getPeerID());
		}
	}

}
